package com.meihua.baoleyi.model;

import android.content.Context;
import android.util.Log;

import com.lzy.okgo.OkGo;
import com.lzy.okgo.callback.StringCallback;
import com.meihua.baoleyi.bean.BaseBean;
import com.meihua.baoleyi.net.LoginC;
import com.meihua.baoleyi.utils.JsonUtils;
import com.meihua.baoleyi.utils.ToastUtil;
import com.meihua.baoleyi.utils.UrlContants;
import com.meihua.baoleyi.view.LoginView;

import okhttp3.Call;
import okhttp3.Response;

/**
 * Name：liming
 * Times: 2017/10/16
 */

public class LoginClass implements LoginC<LoginView> {
    private LoginView mLoginView;
    private Context mContext;

    public LoginClass(LoginView loginView, Context context) {
        mLoginView = loginView;
        mContext = context;
    }

    @Override
    public void login(final String username, final String pwd) {
        OkGo.post("http://10.0.2.130/boleyi/public/api/login/register")
                .tag(this)
                .params("user_phone", username)
                .params("user_password", pwd)
                .execute(new StringCallback() {
                    @Override
                    public void onSuccess(String s, Call call, Response response) {
                        if (s != null) {
                            Object obj = JsonUtils.parse(mContext, s, LoginInfo.class);
                            if (obj != null) {
                                if (obj instanceof LoginInfo) {
                                    LoginInfo loginInfo = (LoginInfo) obj;
                                    if (loginInfo.getCode().equals("200")) {
                                        mLoginView.onLogin(loginInfo);
                                    } else {
                                        mLoginView.onLogin(null);
                                        ToastUtil.show(mContext, loginInfo.getMsg());
                                    }
                                } else if (obj instanceof BaseBean) {
                                    mLoginView.onLogin(null);
                                    ToastUtil.show(mContext, ((BaseBean) obj).getMsg());
                                }
                            }
                        } else {
                            mLoginView.onLogin(null);
                            ToastUtil.show(mContext, "服务器无数据返回！");
                        }
                    }

                    @Override
                    public void onError(Call call, Response response, Exception e) {
                        super.onError(call, response, e);
                        mLoginView.onLogin(null);
                        ToastUtil.show(mContext, "服务器异常！");
                    }
                });
    }

}
